﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LabChecker.ViewModels;
using LabChecker.Models;

namespace LabChecker.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult SignIn()
        {
            return View();
        }

        public ActionResult Register()
        {
            using (var context = new LabCheckerContext())
            {
                var registration = new Registration();
                PopulateRegistrationGroups(context, registration);

                return View(registration);
            }
        }

        [HttpPost]
        public ActionResult Register(Registration registration)
        {
            using (var context = new LabCheckerContext())
            {           
                ModelState.Remove("Student.Group");
                ModelState.Remove("Login.User");
                ModelState.Remove("Login.PasswordHash");

                if (!ModelState.IsValid)
                {
                    goto error;
                }

                var student = registration.Student;
                var login = registration.Login;

                student.Group = context.Groups.Find(registration.SelectedGroupId);
                login.User = student;
                login.PasswordHash = registration.Password;

                if (TryValidateModel(student) && TryValidateModel(login))
                {
                    context.Users.Add(student);
                    context.InternalLogins.Add(login);
                    context.SaveChanges();

                    return RedirectToAction("Index", "Home");
                }

            error:
                PopulateRegistrationGroups(context, registration);
                return View(registration);
            }
        }

        private static void PopulateRegistrationGroups(LabCheckerContext context, Registration registration)
        {
            registration.AllGroups = (from g in context.Groups.ToList()
                                      select new SelectListItem { Text = g.Name, Value = g.Id.ToString() })
                                      .ToList();
        }
    }
}
